package com.nsgf.library.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.nsgf.library.data.bean.Category;
import com.zhht.htzx.R;
import java.util.List;

public class PrimaryCategoryAdapter extends RecyclerView.Adapter<PrimaryCategoryAdapter.ViewHolder> {
    private Context context;
    private List<Category> categories;
    private OnPrimaryCategoryClickListener listener;
    private int selectedPosition = 0;

    public interface OnPrimaryCategoryClickListener {
        void onPrimaryCategoryClick(Category category, int position);
    }

    public PrimaryCategoryAdapter(Context context, List<Category> categories, OnPrimaryCategoryClickListener listener) {
        this.context = context;
        this.categories = categories;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_primary_category, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Category category = categories.get(position);
        holder.primaryCategoryName.setText(category.getTitle());
        holder.itemView.setSelected(position == selectedPosition);

        holder.itemView.setOnClickListener(v -> {
            int clickPosition = holder.getBindingAdapterPosition();
            if (clickPosition != RecyclerView.NO_POSITION) {
                int oldPosition = selectedPosition;
                selectedPosition = clickPosition;
                notifyItemChanged(oldPosition);
                notifyItemChanged(selectedPosition);
                if (listener != null) {
                    listener.onPrimaryCategoryClick(category, selectedPosition);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return categories != null ? categories.size() : 0;
    }

    public void setSelectedPosition(int position) {
        if (position >= 0 && position < getItemCount() && position != selectedPosition) {
            int oldPosition = selectedPosition;
            selectedPosition = position;
            notifyItemChanged(oldPosition);
            notifyItemChanged(selectedPosition);
        }
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView primaryCategoryName;

        ViewHolder(View itemView) {
            super(itemView);
            primaryCategoryName = itemView.findViewById(R.id.primary_category_name);
        }
    }
}